let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
let goodsModel = require('../models/goods')

//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/demo', {useNewUrlParser: true });

mongoose.connection.once('connected', () => {
 console.log("MongoDB connected success")
});

mongoose.connection.on('error', () => {
  console.log("MongoDB connected fail")
 });
 mongoose.connection.on('disconnected', () => {
  console.log("MongoDB connected disconnected")
 });
 


router.get('/list',function(req,res,next){
  //排序
  let sort = req.param('sort');
  let params = {};
//分页
  let page = parseInt(req.param('page'));
  let pageSize = parseInt(req.param('pageSize'));
  let skip = (page-1)*pageSize;
  //价格过滤
  let priceLevel = req.param('priceLevel')
  let priceGt= '',priceLte= '';
  if(priceLevel !='all'){
    switch(priceLevel){
      case '0': priceGt= 0; priceLte= 100; break;
      case '1': priceGt= 100; priceLte= 500; break;
      case '2': priceGt= 500; priceLte= 1000; break;
      case '3': priceGt= 1000; priceLte= 5000; break;
    }
    params={
      salePrice:{
        $gt: priceGt,
        $lte: priceLte
      }
    }
  }
  
  let Goods = goodsModel.find(params).skip(skip).limit(pageSize)
  Goods.sort({ 'salePrice': sort});
  Goods.exec(function(err,doc){
   if(err){
     res.json({
       status:'1',
       msg:err.message
     })
   }else{
     res.json({
       status:'0',
       msg:'',
       result:{
         count: doc.length,
         list: doc
       }
     })
   }
  })
})

//加入购物车
router.post('/addCart',function(req,res,next){
  let userId= req.cookies.userId , productId= req.body.productId;
  let  User = require('../models/user')
  User.findOne({userId},function(err,userDoc){
    if(err){
      res.json({
        status:'1',
        msg:err.message
      })
    }else{
      if(userDoc){
       let goodsItem= '';
       userDoc.cartList.forEach(item => {
         if(item.productId == productId){
           goodsItem = item;
           item.productNum ++;
         }
       });
        if(goodsItem){
          userDoc.save(function(err2,doc2){
            if(err2){
              res.json({
                status:'1',
                msg:err2.message
              })
            }else{
              res.json({
                status:'0',
                msg:'',
                result:'succ'
              })
            }
          })
        }else{
          goodsModel.findOne({productId},function(err,doc){
            if(err){
              res.json({
                status:'1',
                msg:err.message
              })
            }else{
              if(doc){
                doc.productNum=1;
                doc.checked= 1;
                userDoc.cartList.push(doc);
                userDoc.save(function(err4,doc4){
                  if(err4){
                    res.json({
                      status:'1',
                      msg:err4.message
                    })
                  }else{
                    res.json({
                      status:'0',
                      msg:'',
                      result:'succ'
                    })
                  }
                })
                
              }
            }
          })
        }
      }
      

    }
  })
  })
//商品搜索

router.get("/searchItem",function(req,res,next){
  let itemName= req.param('input')
    goodsModel.find({'productName': itemName},function(err,doc){
      if(!err){
        res.json({
          status:'0',
          msg:'',
          result:doc
        })
      }
    })
})
//后台商品列表
router.get('/',function(req,res,next){
  goodsModel.find({},function(err,doc){
    if(err){
      res.json({
      status:'1',
      msg:err.message,
      result:''
      })
    }else{
      res.json({
      status:'0',
      msg:'',
      result:doc
      })
    }
  })
})
//后台删除商品
router.post('/delgoods',function(req,res,next){
let productId = req.body.productId;
goodsModel.remove({'productId':productId},function(err,doc){
    if(err){
      res.json({
      status:'1',
      msg:err.message,
      result:''
      })
    }else{
      res.json({
      status:'0',
      msg:'',
      result:'删除成功'
      })
    }
})
})
//添加商品
router.post('/addgoods',function(req,res,next){
let productName = req.body.productName;
let salePrice = parseInt(req.body.salePrice);
let productNum = parseInt(req.body.productNum)
let productImage = req.body.productImage;
let productId = parseInt(Math.floor(Math.random()*10+100000)+Math.floor(Math.random()*10+100)+Math.floor(Math.random()*10)+Math.floor(Math.random()*10));
let param = {
 productId:productId,
 productName: productName,
 salePrice: salePrice,
 checked:'',
 productNum: productNum,
 productImage: productImage
};
goodsModel.create(param,function(err,doc){
  if(err){
    res.json({
    status:'1',
    msg:err.message,
    result:''
    })
  }else{
    res.json({
    status:'0',
    msg:'',
    result:'添加成功'
    })
  }
})
})

//修改商品信息
router.post('/changegoods',function(req,res,next){
  let salePrice = parseInt(req.body.salePrice);
  let productNum = parseInt(req.body.productNum);
  let productId = req.body.productId
  
  goodsModel.update({"productId":productId},{$set:{
   'salePrice':salePrice,
   'productNum':productNum
  }},function(err,doc){
    if(err){
      res.json({
      status:'1',
      msg:err.message,
      result:''
      })
    }else{
      res.json({
      status:'0',
      msg:'',
      result:'修改成功'
      })
    }
  })
})

 module.exports = router;